package com.share.common.utils;

import com.alibaba.fastjson.JSON;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class PdfUtil {
    public static byte[] fill(File templateFile, Map<String, Object> fillParam) throws Exception {
        //读取本地文件
        byte[] templateBytes = FileUtil.readByte(templateFile);
        return fill(templateBytes, fillParam);
    }

    public static byte[] fill(String templateUrl, Map<String, Object> fillParam) throws Exception {
        //下载模板文件
        byte[] templateBytes = HttpUtil.downFile(templateUrl, null);
        return fill(templateBytes, fillParam);
    }

    public static byte[] fill(byte[] templateBytes, Map<String, Object> fillParam) throws Exception {
        //加载模板pdf文件
        PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(templateBytes));

        //编辑后的pdf文件缓冲区
        ByteArrayOutputStream outPdfBaos = new ByteArrayOutputStream();

        PdfDocument pdfDocument = new PdfDocument(pdfReader, new PdfWriter(outPdfBaos));
        PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDocument, true);

        //获取pdf文档中的填充
        Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
        Set<String> keys = formFields.keySet();
        log.info("pdf填充,模板表单={},输入的map={}", JSON.toJSONString(keys), JSON.toJSONString(fillParam));
        for (String key : keys) {
            PdfFormField field = formFields.get(key);
            Object o = fillParam.get(key);
            field.setValue(o == null ? null : o.toString());
        }

        // 创建盖章图片
//        PdfCanvas pdfCanvas  = new PdfCanvas()
//        ImageData imageData = ImageDataFactory.create(new URL(imageUrl));
//        PdfImageXObject image = new PdfImageXObject(imageData);
//
//        pdfDocument.setAutoScale(true); // 设置宽高字段缩放
//        pdfDocument.get.getAnnotations().add(image);// 将图片添加到文档上面

        // 关闭文档
        pdfDocument.close();
        return outPdfBaos.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("idCard", "4211261992");
        map.put("name", "孙艳强");
        map.put("createTime", "2024/8/20 22:22:22");
        byte[] fill = fill(new File("C:\\Users\\Administrator\\Desktop\\个人授权书_模板.pdf"), map);
        FileUtil.write(new File("f.pdf"), fill);
    }
}
